var curAnchorid
var curAnchorName
var specialAnchorIds
var rsUserName
var privateChatUploadApi
var curSessionId
var Talk = function () {
    var _this = this;
    this.is_init = true;//是否首次加载
    this.session_id = $('#oneChatBaseInfo').data('sessionid');
    this.user = { id: 0, nick_name: "" }
    this.talk_type = 0; //聊天类型 0私聊，1群聊
    this.is_request = false;
    this.msg_page = 2;//点击后默认加载第一页聊天内容，所以默认page设置2
    this.not_msg = false;
    this.elem = { talks: $('#imTalkList'), write: $('#writeContent') };
    this.talk_scroll = { top: 0, is_bottom: false, height: 0 };//聊天滚动条
    this.html = {
        talk_msg: '<dl class="chat_cont_info"><dt></dt><spana style="display:block;"></spana><dd></dd></dl>',//聊天消息主html
    };
    this.is_send = false;// 是否正在发送中
    this.socket = new Websocket();
    this.socket.connect();//直接连接socket
    /**
     * 初始化
     */
    this.init = function () {
        // 私聊
        if (_this.session_id.id != "") {
            _this.get.init_talks();
            // 右侧区域设置显示内容
            $('#chatRightArea').removeClass('layui-hide')
            $('#chatNotArea').addClass('layui-hide')
        }
        this.monitor_scroll();
    };

    /**
     * socket接收消息事件
     * @param data 接收的消息对象
     */
    this.socket.onmessage = function (data) {
        if (typeof data.type == 'undefined') {
            return;
        }
        switch (data.type) {
            // 私聊消息
            case 'say':
                _this.set.show_msg_page(data.data);
                break;
            // 群聊消息
            case 'group_say':
                _this.group.show_msg_page(data.data);
                break;
        }
    };

    /**
     * 发送消息
     */
    this.send = {
        /**
         * 输入框文本消息
         */
        text: function () {
            //提取输入框内的内容
            var msg_content = $.trim(_this.elem.write.val());
            //判断长度的时候把img标签替换成一个字符
            var content_len = msg_content.replace(/\n/g, '').length;
            if (content_len < 1 || content_len > 300) {
                layer.msg('输入字符数量请保持在1~300之间！</br>当前内容长度为：' + content_len);
                return false;
            }

            //保存消息
            this.save(msg_content, 1);
        },
        /**
         * 保存消息
         */
        save: function (msg_content, msType) {
            if (_this.is_send) {
                return;
            }
            _this.is_send = true;
            console.log("_this.session_id", _this.session_id)
            // 发送群聊还是私聊信息
            let send_url = '/admin/privatechat/send_chat';
            let send_data = { 'session_id': _this.session_id, 'content': msg_content, 'group_id': curAnchorid, 'msg_type': msType };

            $.ajax({
                url: send_url,
                type: 'post',
                dataType: 'json',
                data: send_data,
                timeout: 10000,
                success: function (res) {
                    if (res.code == 0) {
                        _this.elem.write.val('');
                    } else {
                        layer.msg(res.msg);
                    }
                },
                error: function (err) {
                    _this.is_send = false;
                    layer.msg('系统异常,请稍后再试!');
                },
                complete: function () {
                    _this.is_send = false;
                    layer.closeAll('loading');
                }
            });
        },

    };

    this.set = {
        /**
         * 显示消息在页面上
         */
        show_msg_page: function (info) {
            var ddExists = $('.chatList dl').find(`dd[data-sessionid="${info.session_id}"]`).length > 0
            // console.log("存在:",ddExists,"info.anchor_id:",info.anchor_id,"当前_this.anchor.id:",curAnchorid )
            if (!ddExists && info.anchor_id == curAnchorid) {
                getSessionList(info.anchor_id)
            }
            // 设置左侧消息内容
            if (_this.session_id != info.session_id) {
                setTopUnread(info.anchor_id, 1)
                setSessionIdUnread(info.session_id)
                console.log("当前session_id:", _this.session_id, "info session_id:", info.session_id)
                return;
            }

            $('.chatList dl').find(`dd[data-sessionid="${info.session_id}"]`).find('.last_reply_msg').html(content);

            var html_elem = $(_this.html.talk_msg).data(info);


            if (info.receive_uid != curAnchorid) {
                html_elem.addClass('anchor_send');
                html_elem.find('dt').html('<span>' + common.format_time_bak(info.send_time) + '</span>我');
            } else {
                html_elem.find('dt').html(_this.user.nick_name + '<span>' + common.format_time_bak(info.send_time) + '</span>');
            }

            if (info.img_url) {
                setImg(html_elem, info.send_time, info.img_url, info.id, _this.session_id);
            }
            if (info.content) {
                var content = info.content.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>');
                html_elem.find('dd').html(content);
            } else {
                html_elem.find('dd').remove()
            }

            _this.elem.talks.find('#notMsg').remove();
            _this.elem.talks.append(html_elem);
            //将聊天区域的DIV滚动条，滚动到最底部 
            common.scroll_to_bottom(_this.elem.talks);

            return html_elem;
        },

        /**
         * 右侧页面加载后，用户信息设置
         * @param chat_session
         */
        user_set: function (chat_session) {
            var html_elem = $('#chatUserInfo');

            // 设置私聊id信息
            _this.session_id = chat_session;
            console.log("获得chat_session", chat_session)
            $('#oneChatBaseInfo').data('sessionid', _this.session_id);
            $('.chatList dl').find(`dd[data-userid="${_this.user.id}"]`).data('sessionid', _this.session_id);

            html_elem.data();
        },
    };

    this.get = {
        /**
         * 加载页面获取聊天内容
         */
        init_talks: function () {
            if (_this.is_request) {
                return false;
            }
            $("#anchorId").html("<font color='green'>" + rsUserName + "</font>用户，通过<font color='blue'>" + curAnchorName + "</font>的直播间发起. <b>渠道号:"+curChannel+"</b>")
            _this.is_request = true;
            _this.not_msg = false;
            var loading = '<div class="page_loading" id="msgLoading"><i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i><span>聊天内容加载中...</span></div>';//加载中显示的元素
            var loading_error = '<div class="talk_load_error" id="msgLoadingErr">加载失败!<span class="reload" id="talksReload">重试</span></div>';//加载失败显示的元素
            $.ajax({
                url: '/admin/privatechat/get_chat_content',
                type: 'get',
                dataType: 'json',
                timeout: 5000,
                data: { anchor_id: curAnchorid, sort: 'desc', 'session_id': _this.session_id },
                beforeSend: function (xhr) {
                    _this.elem.talks.html(loading);//显示加载中
                },
                success: function (res) {
                    if (res.list.length === 0) {
                        _this.elem.talks.html('<div class="page_loading" id="notMsg">暂无任何聊天内容...</div>');//显示无数据提示
                        //return false;
                    }
                    curUnreadNum = $("#unread_" + _this.session_id).text()
                    setTopUnread(curAnchorid, -curUnreadNum)
                    $("#unread_" + _this.session_id).remove()
                    //获取到的json转换成html
                    var msg_elem = _this.get.talks_html(res);
                    console.log("msg_elem:", msg_elem)
                    //如果没有发送失败的消息，直接显示获取到的消息到页面上
                    _this.elem.talks.html(msg_elem);
                    //滚动条滚动到底部
                    common.scroll_to_bottom(_this.elem.talks);
                    //判断消息内容数量
                    if (_this.elem.talks.find('.chat_cont_info').length < 1) {
                        _this.not_msg = true;
                    }
                    if (_this.is_init) {
                        _this.is_init = false;
                    }

                },
                error: function (xhr, status, error) {
                    _this.elem.talks.html(loading_error);

                },
                complete: function (xhr, status) {
                    _this.is_request = false;
                }
            });
        },
        /**
         * 获取历史聊天记录
         */
        history_talks: function () {
            if (_this.is_request || _this.not_msg) {
                return false;
            }
            _this.is_request = true;
            $('#moreMsgLoadingErr, #notHistoryMsg').remove();
            _this.elem.talks.prepend('<div class="more_msg_loading" id="moreMsgLoading"><i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>加载中...</div>');//显示加载中

            // 获取第一个dl的发送时间
            var first_send_time = _this.elem.talks.find('dl').length > 0 ? _this.elem.talks.find('dl').first().data('send_time') : 0;
            $.ajax({
                url: '/admin/privatechat/get_chat_content',
                type: 'get',
                dataType: 'json',
                timeout: 3000,
                data: {
                    anchor_id: curAnchorid,
                    sort: 'desc',
                    'session_id': _this.session_id,
                    "time": first_send_time
                },
                beforeSend: function (xhr) {
                },
                success: function (res) {
                    if (res.list.length === 0) {
                        _this.elem.talks.prepend('<div class="not_history_msg" id="notHistoryMsg">没有更多历史消息了~</div>');
                        _this.not_msg = true;
                        return false;
                    }
                    var scroll_height = _this.elem.talks[0].scrollHeight;
                    //获取到的json转换成html
                    var msg_elem = _this.get.talks_html(res);
                    _this.elem.talks.prepend(msg_elem);
                    //内容插入到上面后保持滚动条不动
                    _this.elem.talks.scrollTop(_this.elem.talks[0].scrollHeight - scroll_height - 50);
                    _this.msg_page++;
                },
                error: function (xhr, status, error) {
                    //加载失败显示失败的元素
                    _this.elem.talks.prepend('<div class="more_msg_load_error" id="moreMsgLoadingErr">加载失败!</div>');
                },
                complete: function (xhr, status) {
                    $('#moreMsgLoading').remove();
                    _this.is_request = false;
                }
            });

        },

        /**
         * 聊天消息json转html
         * @param {object} data 聊天数据
         */
        talks_html: function (data) {
            var html_elem = $();
            $.each(data.list, function (k, v) {
                if ($('#' + v._id).length > 0) {
                    //如果消息已存在页面上,跳过
                    return true;
                }

                var elem = $(_this.html.talk_msg).attr('id', v._id).data(v);
                if (v.sender_uid == curAnchorid) {
                    elem.addClass('anchor_send');
                    elem.find('dt').html('<span>' + common.format_time_bak(v.send_time) + '</span>我');
                } else {
                    if (v.role == 1) {
                        elem.find('dt').html(_this.user.nick_name + '<span style="background-color: #02A8A2;padding:0px 8px;font-size:14px;color:#FFF;border-radius:5px;margin-left: 5px;">房管</span><span>' + common.format_time_bak(v.send_time) + '</span>');
                    } else {
                        elem.find('dt').html(_this.user.nick_name + '<span>' + common.format_time_bak(v.send_time) + '</span>');
                    }
                }
                console.log("privateChatData",data)
                if (v.img_url) {
                    setImg(elem, v.send_time, v.img_url,v.id, _this.session_id)
                }
                if (v.content) {
                    elem.find('dd').html(`${v.content}<span class="revoke_msg" data-content="${v.content}" data-index="${v.id}" data-anchorid="${curAnchorid}" data-sessionid="${_this.session_id}">撤回</span>`);
                } else {
                    elem.find('dd').remove()
                }
                elem.on('click', '.revoke_msg', function() {
                    let index = $(this).data('index');
                    let content = $(this).data('content');
                    let anchorid = $(this).data('anchorid');
                    let sessionid = $(this).data('sessionid');
                    delChatMsg(index, content, $(this), anchorid, sessionid);
                });
                html_elem.push(elem[0]);
            });
            return html_elem;
        }
    };

    /**
     * 监听聊天框滚动条
     */
    this.monitor_scroll = function () {
        _this.elem.talks.scroll(function () {
            _this.talk_scroll.top = $(this)[0].scrollTop;
            _this.talk_scroll.height = $(this)[0].scrollHeight;
            var im_talk_height = $(this)[0].clientHeight;
            if (_this.talk_scroll.height > im_talk_height && (_this.talk_scroll.top + im_talk_height) >= (_this.talk_scroll.height - 120)) {
                _this.talk_scroll.is_bottom = true;
                _this.msg_page = 2;
                _this.not_msg = false;
            } else {
                _this.talk_scroll.is_bottom = false;
            }
            if (common.is_show_scroll($(this)) == true && _this.talk_scroll.top == 0) {
                if (_this.talk_type == 1) {
                    _this.group.history_talks();
                } else {
                    _this.get.history_talks();
                }
            }
        });
    };

};


var common = {
    /**
     * 是否出现滚动条
     * @param elem 滚动区域的jq对象
     * @returns {boolean}
     */
    is_show_scroll: function (elem) {
        return (elem[0].scrollHeight > elem[0].clientHeight || elem[0].offsetHeight > elem[0].clientHeight);
    },
    /**
     * 滚动条到底部
     */
    scroll_to_bottom: function (elem) {
        elem.scrollTop(elem[0].scrollHeight);
    },

    format_time: function (time_stamp) {
        //time_stamp = parseInt(time_stamp / 1000) * 1000;
        time_stamp = parseInt(time_stamp * 1000);

        const time = new Date(time_stamp);
        const Y = time.getFullYear();
        const M = (time.getMonth() + 1).toString().padStart(2, "0");
        const D = time.getDate().toString().padStart(2, "0");
        const h = time.getHours().toString().padStart(2, "0");
        const m = time.getMinutes().toString().padStart(2, "0");
        const s = time.getSeconds().toString().padStart(2, "0");
        return `${Y}-${M}-${D} ${h}:${m}:${s}`;
    },
    format_time_bak: function (time_stamp) {
        time_stamp = parseInt(time_stamp / 1000) * 1000;

        const time = new Date(time_stamp);
        const Y = time.getFullYear();
        const M = (time.getMonth() + 1).toString().padStart(2, "0");
        const D = time.getDate().toString().padStart(2, "0");
        const h = time.getHours().toString().padStart(2, "0");
        const m = time.getMinutes().toString().padStart(2, "0");
        const s = time.getSeconds().toString().padStart(2, "0");
        return `${Y}-${M}-${D} ${h}:${m}:${s}`;
    }
};

var Websocket = function () {
    var _this = this;
    //创建websocket
    this.ws_conn = null;
    //连接状态
    this.web_socket = { close: 0, error: 0 };
    this.timer = 0;

    /**
     * 发送WebSocket连接请求
     */
    this.connect = function () {
        var ws_conn_url = private_chat_ws;
        console.log("ws_conn_url:", ws_conn_url)
        //判断当前浏览器是否支持WebSocket
        if ('WebSocket' in window) {
            _this.ws_conn = new WebSocket(ws_conn_url);
        } else if ('MozWebSocket' in window) {
            _this.ws_conn = new MozWebSocket(ws_conn_url);
        } else {
            alert('对不起，您当前的浏览器不支持实时通讯功能，建议使用谷歌浏览器！');
            throw "stop!";
        }
        //连接成功触发open事件
        _this.ws_conn.onopen = function (e) {
            _this.onopen(e);
        };
        //消息接收事件
        _this.ws_conn.onmessage = function (e) {
            console.log("收到消息:", e.data)
            var data = JSON.parse(e.data);
            _this.onmessage(data);
        };
        //连接断开
        _this.ws_conn.onclose = function (e) {
            _this.onclose(e);
            if (_this.web_socket.close == 0) {
                window.clearTimeout(_this.timer);
                //每3秒重连一次
                _this.timer = setTimeout(function () {
                    _this.connect();
                }, 3000);
            }
        };
        _this.ws_conn.onerror = function (e) {
            _this.web_socket.error = 1;
            console.log("WebSocket出现异常错误！");
        };
        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            _this.web_socket.close = 1;
            _this.ws_conn.close();
        };
    };
    //连接成功事件
    this.onopen = function (e) {
        console.log('连接成功!');
    };
    //消息接收事件
    this.onmessage = function (e) {
    };
    //断开连接事件
    this.onclose = function (e) {
        console.log('断开连接!');
    };
    //发送消息
    this.send = function (data_obj) {
        var json_str = JSON.stringify(data_obj);
        _this.ws_conn.send(json_str);
    };

};

function setTopUnread(anchor_id, n) {
    var specialid = getSpecialAnchorId(anchor_id)

    if (specialid != "") {
        anchor_id = specialid
    }

    var unread = parseInt($("#top_unread_" + anchor_id).attr("data-topunread"))
    console.log("anchor_id:", anchor_id, "unread:", unread, "specialid:", specialid)
    unread = isNaN(unread) ? 0 : unread;
    var anchorName = $("#top_" + anchor_id).find("span:first").text()
    unread += n
    if (unread < 1) {
        $("#top_" + anchor_id).find("span").not(":first").remove()
        return
    }
    $("#top_" + anchor_id).html(`<span>${anchorName}</span><span class="chat-tab-btn-note" id="top_unread_${anchor_id}" data-topunread="${unread}">${unread}</span>`)
}

function setSessionIdUnread(session_id) {
    var unread = parseInt($("#unread_" + session_id).text())
    unread = isNaN(unread) ? 0 : unread;
    unread += 1
    if (unread == 1) {
        var pl = `<p  id="unread_${session_id}" style="width:15px; height:15px; background-color: #EC6353; padding:3px;color:white; border-radius: 15px; display: flex; justify-content: center; align-items: center;">${unread}</p>`
        console.log("未读数:", unread, "pl", pl)
        $("#lastmsg_" + session_id).after(pl)
    } else {
        $("#unread_" + session_id).text(unread)
    }
}

function getSessionList(anchor_id) {
    $('.inTalk').html('');
    layer.load()
    $.ajax({
        url: '/admin/privatechat/getPrivateChatList',
        type: 'get',
        data: { "anchorid": anchor_id },
        dataType: 'json',
        beforeSend: function (xhr) {
            //_this.elem.talks.html(loading);//显示加载中
        },
        success: function (res) {
            if (res.length == 0) {
                return
            }
            $.each(res, function (i, item) {
                var html = `<dl class="admin">`;
                // 页面上是否存在管理员正在私聊
                var chat_list_obj = $('.inTalk');
                html += `<dd id="${item.ConversationId}" data-userid="${item.UserId}" data-username="${item.UserName}" data-anchorid="${item.AnchorId}" data-anchorname="${item.AnchorName}" data-sessionid="${item.ConversationId}" data-rsUserName="${item.RsUserName}" data-channel="${item.Channel}" data-Ban="${item.Ban}">`;
                html += `<div class="device_icon"><img src="${item.UserAvatar}"></div>`
                html += `<div class="user_chat_desc">`
                html += `<p>${item.UserName}</p>`
                html += `<div class="chat-msg-wrap"><p class="last_reply_msg" id="lastmsg_${item.ConversationId}">${item.LatestMsgTime}</p>`
                if (item.Unread > 0) {
                    html += `<p  id="unread_${item.ConversationId}" style="width:15px; height:15px; background-color: #EC6353; padding:3px;color:white; border-radius: 15px; display: flex; justify-content: center; align-items: center;">${item.Unread}</p>`
                }
                html += '</div></div></dd></dl>'
                chat_list_obj.append(html)
            });
        },
        error: function (err) {
            layer.msg('系统异常,请稍后再试!');
        },
        complete: function () {
            layer.closeAll('loading');
        }
    });
}

function getSpecialAnchorId(aid) {
    sid = "";
    var specialAnchorData = $.parseJSON(specialAnchorIds);
    specialAnchorData.g1.forEach(function (v, k) {
        if (v == aid) {
            sid = "g1"
            return false
        }
    });
    specialAnchorData.g2.forEach(function (v, k) {
        console.log("aid:", aid, "v:", v)
        if (v == aid) {
            sid = "g2"
            return false
        }
    });
    specialAnchorData.g3.forEach(function (v, k) {
        if (v == aid) {
            sid = "g3"
            return false
        }
    });
    return sid
}

function translateBase64ImgToBlob(base64, index) {
    var arr = base64.split(","); //去掉base64格式图片的头部
    var bstr = atob(arr[1]); //atob()方法将数据解码
    bstr = bstr.slice(0, 4) + bstr.slice(13);
    var leng = bstr.length;
    var u8arr = new Uint8Array(leng);
    while (leng--) {
        u8arr[leng] = bstr.charCodeAt(leng); //返回指定位置的字符的 Unicode 编码
    }
    var blob = new Blob([u8arr]);
    let blobImg = URL.createObjectURL(blob); //创建URL,
    return blobImg;

}


var upload = layui.upload;

//常规使用 - 普通图片上传
var choosefile;
var files = null;

console.log("privateChatUploadApi", privateChatUploadApi)
//layer.load();
var uploadInst = upload.render({
    elem: "#private_img",
    url: "https://images.lmim1.com/api/uploader", //此处用的是第三方的 http 请求演示，实际使用时改成您自己的上传接口即可。
    before: function (obj) {
        //预读本地文件示例，不支持ie8
        // obj.preview(function (index, file, result) {
        //     choosefile = file;
        //     $("#send2").attr("src", result); //图片链接（base64）
        // });
        layer.load();
    },
    choose: function (obj) {
        deletefile()
        files = obj.pushFile();
    },
    done: function (res) {//上传完成后回调
        deletefile();
        if (res.status == 0) {
            talk.session_id = curSessionId
            talk.send.save(res.data, 2)
        } else {
            layer.msg(res.msg, { icon: 5 });
            return false;
        }
    },
    //进度条
    progress: function (n, elem, e) {
        var percent = n + '%' //获取进度百分比
        //element.progress('#upload_excel_'+inde, percent);
        console.log("获取进度百分比:", percent);
    },
});

function deletefile() {
    if (null != files) {
        for (var i = 0; i < Object.keys(files).length; i++) {
            delete files[Object.keys(files)[i]];
        }
        files = null;

    }
}


function setImg(elem, sid, img_url, id, sessionId) {
    var imgid = 'img_' + sid
    elem.find('spana').html(`'<img id="${imgid}" src="${img_url}" width="400"><span class="revoke_msg" data-content="${img_url}" data-index="${id}" data-anchorid="${curAnchorid}" data-sessionid="${sessionId}">撤回</span>'`);
    return;
    //如果图片加密，开启以下代码
    var xhr = new XMLHttpRequest();
    // 设置请求的类型和URL
    xhr.open('GET', img_url, true);
    // 设置响应类型为blob
    xhr.responseType = 'blob';
    var imgStr = "";
    // 当请求完成时执行此函数
    xhr.onload = function (e) {
        if (this.status == 200) {
            const file = this.response;
            const reader = new FileReader();
            reader.onload = (event) => {
                str = event.currentTarget.result
                imgStr = translateBase64ImgToBlob(str)
                $("#" + imgid).attr("src", imgStr)
            };
            reader.readAsDataURL(file)
        }
    };
    // 发送请求
    xhr.send();
}

function delChatMsg(id, content, elem, anchorid, sessionid) {
    console.log("delChatMsg", anchorid, sessionid, content, id);
    // 添加确认弹窗
    layer.confirm('确定要撤回这条消息吗?', {
        btn: ['确定','取消'], 
        title: '提示'
    }, function(index){
        // 点击确定后执行
        $.ajax({
            url: '/admin/privatechat/del_private_chat',
            type: 'post',
            data: { 
                "id": id,
                "send_id": anchorid,
                "sid": sessionid,
                "content": content
            },
            dataType: 'json',
            success: function (res) {
                // 删除成功后移除元素
                elem.parent().parent().remove();
                layer.msg(res.msg);
                layer.closeAll('loading');
            },
            error: function (err) {
                console.log('系统异常:'+ err)
            },
            complete: function () {
                layer.closeAll('loading');
            }
        });
        layer.close(index);
    });
}